<template>
  <el-dialog v-model="addRoleVisible" :title="roleId === 0 ? '创建角色' : '编辑角色'" width="600">
    <el-steps style="max-width: 600px; margin-bottom: 20px" :active="active" finish-status="success" simple>
      <el-step title="填写名称描述" />
      <el-step title="管理权限分配" />
    </el-steps>
    <!--    步骤一    -->
    <el-form
      ref="formRef"
      v-if="active === 1"
      style="max-width: 600px"
      :model="formCustom"
      status-icon
      :rules="rules"
      label-width="auto"
    >
      <el-form-item label="名称" prop="name">
        <el-input v-model="formCustom.name" type="text" autocomplete="off" />
      </el-form-item>
      <el-form-item label="描述" prop="desc">
        <el-input v-model="formCustom.desc" type="textarea" autocomplete="off" />
      </el-form-item>
    </el-form>
    <!--    步骤二    -->
    <div v-if="active === 2">
      <TreeFilter
        label="name"
        title=""
        :default-expand-all="false"
        :multiple="true"
        :data="treeFilterData"
        :default-value="checkedPermission"
        :checked-leaf="true"
        @change="changeTreeFilter"
      />
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="previous" v-if="active === 2">上一步</el-button>
        <el-button type="primary" @click="next(formRef)" v-if="active === 1">下一步</el-button>
        <el-button type="primary" @click="submit(formRef)" :loading="loading" v-if="active === 2">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts" name="AddOrEditRole">
import { ref, reactive } from "vue";
import { createRole, getPermissionList, getRoleDetail, roleModify } from "@/api/modules/roleManagement";
import { ElMessage } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";
import TreeFilter from "@/components/TreeFilter/index.vue";
const formRef = ref<FormInstance>();
// 角色id
let roleId: any = 0;
// const validatePass = (rule: any, value: any, callback: any) => {
//   if (value === "") {
//     callback(new Error("Please input the password"));
//   } else {
//     if (ruleForm.checkPass !== "") {
//       if (!formRef.value) return;
//       formRef.value.validateField("checkPass");
//     }
//     callback();
//   }
// };

// 第一步
const formCustom = reactive({
  name: "",
  desc: ""
});
const rules = reactive<FormRules<typeof formCustom>>({
  name: [
    { required: true, message: "不能为空", trigger: "blur" },
    { required: true, message: "长度需为0~64个字符", min: 0, max: 64, trigger: "blur" }
  ],
  desc: [{ min: 0, max: 500, message: "长度需为0~500个字符", trigger: "blur" }]
});

// 获取 treeFilter 数据
// 当 proTable 的 requestAuto 属性为 false，不会自动请求表格数据，等待 treeFilter 数据回来之后，更改 initParam.org_id 的值，才会触发请求 proTable 数据
const treeFilterData = ref<any>([]);
const getTreeFilter = async () => {
  const { data } = await getPermissionList();
  treeFilterData.value = data;
};
const checkedPermission = ref<any[]>([]);
// 获取角色详情
const getDetail = async () => {
  checkedPermission.value = [];
  const { data } = await getRoleDetail(roleId);
  formCustom.name = data.name;
  formCustom.desc = data.desc;
  checkedPermission.value = data.permission_ids;
};

let loading = false;
// const checkedUsers = ref<any[]>([]);
// 关联用户
const addRoleVisible = ref<boolean>(false);
const openDialog = (id: number = 0) => {
  roleId = id;
  loading = false;
  checkedPermission.value = [];
  // 重置表单
  formCustom.name = "";
  formCustom.desc = "";
  active.value = 1;
  addRoleVisible.value = true;
  getTreeFilter();
  if (roleId !== 0) {
    getDetail();
  }
};
const closeDialog = () => {
  loading = false;
  addRoleVisible.value = false;
};
const active = ref(1);
const previous = () => {
  active.value--;
};
const next = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(valid => {
    if (valid) {
      active.value++;
    }
  });
};

// let checkPermissionList = [];
const changeTreeFilter = (data: any) => {
  checkedPermission.value = data;
};
// emit
const emit = defineEmits<{
  refresh: [];
}>();

const submit = async (formEl: FormInstance | undefined) => {
  loading = true;
  const paramsObj = { ...formCustom, permission_ids: checkedPermission.value };
  if (roleId === 0) {
    // 创建
    const { data } = await createRole(paramsObj);
    if (data) {
      ElMessage({
        type: "success",
        message: `操作成功!`
      });
      addRoleVisible.value = false;
      // 重置表单
      formCustom.name = "";
      formCustom.desc = "";
      active.value = 1;
      emit("refresh");
    }
  } else {
    // 编辑
    const { data } = await roleModify(roleId, paramsObj);
    if (data) {
      ElMessage({
        type: "success",
        message: `操作成功!`
      });
      addRoleVisible.value = false;
      // 重置表单
      formEl?.resetFields();
      active.value = 1;
      emit("refresh");
    }
  }
};
defineExpose({
  openDialog,
  closeDialog
});
</script>
<style lang="scss" scoped>
.filter {
  width: 100%;
  height: 500px;
  overflow-y: auto;
  border: none;
  box-shadow: none;
}
</style>
